<!DOCTYPE html>
<html lang=en>
<head>
    <!-- so meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="HandheldFriendly" content="True">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5" />
    <meta name="description" content="前言使用Spring Security OAuth2时，源码对于返回消息没有做一个统一的封装。为了统一规范，我们可以采取一些措施。 下图是原初访问**&#x2F;oauth&#x2F;token**获取token时，成功和失败（源码抛出异常时的响应示例）   基于AOP的切点表示式观察控制台日志： 12023-03-16 14:55:08.940  WARN 25476 --- [io-63070">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringSecurityOAuth2的自定义返回方案">
<meta property="og:url" content="https://cheung0-bit.github.io/e4b16aee6d6d/index.html">
<meta property="og:site_name" content="Bruce Zhang&#39;s Blogs">
<meta property="og:description" content="前言使用Spring Security OAuth2时，源码对于返回消息没有做一个统一的封装。为了统一规范，我们可以采取一些措施。 下图是原初访问**&#x2F;oauth&#x2F;token**获取token时，成功和失败（源码抛出异常时的响应示例）   基于AOP的切点表示式观察控制台日志： 12023-03-16 14:55:08.940  WARN 25476 --- [io-63070">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316145452918.png">
<meta property="og:image" content="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316145519096.png">
<meta property="og:image" content="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316145920029.png">
<meta property="og:image" content="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316150151554.png">
<meta property="og:image" content="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316150205344.png">
<meta property="og:image" content="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316154512487.png">
<meta property="og:image" content="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316154522929.png">
<meta property="article:published_time" content="2023-03-16T06:49:13.000Z">
<meta property="article:modified_time" content="2023-11-30T12:21:14.047Z">
<meta property="article:author" content="张林">
<meta property="article:tag" content="Spring Security OAuth2">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316145452918.png">
    
    
      
        
          <link rel="shortcut icon" href="/images/favicon.ico">
        
      
      
        
          <link rel="icon" type="image/png" href="/images/favicon-192x192.png" sizes="192x192">
        
      
      
        
          <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png">
        
      
    
    <!-- title -->
    <title>SpringSecurityOAuth2的自定义返回方案</title>
    <!-- styles -->
    
<link rel="stylesheet" href="/css/style.css">

    <!-- persian styles -->
    
    <!-- rss -->
    
    
      <link rel="alternate" href="/atom.xml" title="Bruce Zhang&#39;s Blogs" type="application/atom+xml" />
    
	<!-- mathjax -->
	
<meta name="generator" content="Hexo 7.0.0"></head>

<body class="max-width mx-auto px3 ltr">
    
      <div id="header-post">
  <a id="menu-icon" href="#" aria-label="Menu"><i class="fas fa-bars fa-lg"></i></a>
  <a id="menu-icon-tablet" href="#" aria-label="Menu"><i class="fas fa-bars fa-lg"></i></a>
  <a id="top-icon-tablet" href="#" aria-label="Top" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');" style="display:none;"><i class="fas fa-chevron-up fa-lg"></i></a>
  <span id="menu">
    <span id="nav">
      <ul>
        <!--
       --><li><a href="/">Home</a></li><!--
     --><!--
       --><li><a href="/about/">About</a></li><!--
     --><!--
       --><li><a href="/archives/">Articles</a></li><!--
     --><!--
       --><li><a href="/categories/">Category</a></li><!--
     --><!--
       --><li><a href="/search/">Search</a></li><!--
     -->
      </ul>
    </span>
    <br/>
    <span id="actions">
      <ul>
        
        <li><a class="icon" aria-label="Previous post" href="/ee67649bbccb/"><i class="fas fa-chevron-left" aria-hidden="true" onmouseover="$('#i-prev').toggle();" onmouseout="$('#i-prev').toggle();"></i></a></li>
        
        
        <li><a class="icon" aria-label="Next post" href="/cbba33b008f0/"><i class="fas fa-chevron-right" aria-hidden="true" onmouseover="$('#i-next').toggle();" onmouseout="$('#i-next').toggle();"></i></a></li>
        
        <li><a class="icon" aria-label="Back to top" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up" aria-hidden="true" onmouseover="$('#i-top').toggle();" onmouseout="$('#i-top').toggle();"></i></a></li>
        <li><a class="icon" aria-label="Share post" href="#"><i class="fas fa-share-alt" aria-hidden="true" onmouseover="$('#i-share').toggle();" onmouseout="$('#i-share').toggle();" onclick="$('#share').toggle();return false;"></i></a></li>
      </ul>
      <span id="i-prev" class="info" style="display:none;">Previous post</span>
      <span id="i-next" class="info" style="display:none;">Next post</span>
      <span id="i-top" class="info" style="display:none;">Back to top</span>
      <span id="i-share" class="info" style="display:none;">Share post</span>
    </span>
    <br/>
    <div id="share" style="display: none">
      <ul>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.facebook.com/sharer.php?u=https://cheung0-bit.github.io/e4b16aee6d6d/"><i class="fab fa-facebook " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://twitter.com/share?url=https://cheung0-bit.github.io/e4b16aee6d6d/&text=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-twitter " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.linkedin.com/shareArticle?url=https://cheung0-bit.github.io/e4b16aee6d6d/&title=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-linkedin " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://pinterest.com/pin/create/bookmarklet/?url=https://cheung0-bit.github.io/e4b16aee6d6d/&is_video=false&description=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-pinterest " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=SpringSecurityOAuth2的自定义返回方案&body=Check out this article: https://cheung0-bit.github.io/e4b16aee6d6d/"><i class="fas fa-envelope " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://getpocket.com/save?url=https://cheung0-bit.github.io/e4b16aee6d6d/&title=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-get-pocket " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://reddit.com/submit?url=https://cheung0-bit.github.io/e4b16aee6d6d/&title=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-reddit " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.stumbleupon.com/submit?url=https://cheung0-bit.github.io/e4b16aee6d6d/&title=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-stumbleupon " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://digg.com/submit?url=https://cheung0-bit.github.io/e4b16aee6d6d/&title=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-digg " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.tumblr.com/share/link?url=https://cheung0-bit.github.io/e4b16aee6d6d/&name=SpringSecurityOAuth2的自定义返回方案&description="><i class="fab fa-tumblr " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://news.ycombinator.com/submitlink?u=https://cheung0-bit.github.io/e4b16aee6d6d/&t=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-hacker-news " aria-hidden="true"></i></a></li>
</ul>

    </div>
    <div id="toc">
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E4%BA%8EAOP%E7%9A%84%E5%88%87%E7%82%B9%E8%A1%A8%E7%A4%BA%E5%BC%8F"><span class="toc-number">2.</span> <span class="toc-text">基于AOP的切点表示式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E4%BA%8E%E5%85%A8%E5%B1%80MVC%E5%A2%9E%E5%BC%BA"><span class="toc-number">3.</span> <span class="toc-text">基于全局MVC增强</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">4.</span> <span class="toc-text">总结</span></a></li></ol>
    </div>
  </span>
</div>

    
    <div class="content index py4">
        
        <article class="post" itemscope itemtype="http://schema.org/BlogPosting">
  <header>
    
    <h1 class="posttitle" itemprop="name headline">
        SpringSecurityOAuth2的自定义返回方案
    </h1>



    <div class="meta">
      <span class="author" itemprop="author" itemscope itemtype="http://schema.org/Person">
        <span itemprop="name">张林</span>
      </span>
      
    <div class="postdate">
      
        <time datetime="2023-03-16T06:49:13.000Z" itemprop="datePublished">2023-03-16</time>
        
        (Updated: <time datetime="2023-11-30T12:21:14.047Z" itemprop="dateModified">2023-11-30</time>)
        
      
    </div>


      
    <div class="article-category">
        <i class="fas fa-archive"></i>
        <a class="category-link" href="/categories/%E5%BC%80%E5%8F%91%E5%AE%9E%E8%B7%B5/">开发实践</a>
    </div>


      
    <div class="article-tag">
        <i class="fas fa-tag"></i>
        <a class="tag-link-link" href="/tags/Spring-Security-OAuth2/" rel="tag">Spring Security OAuth2</a>
    </div>


    </div>
  </header>
  

  <div class="content" itemprop="articleBody">
    <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>使用Spring Security OAuth2时，源码对于返回消息没有做一个统一的封装。为了统一规范，我们可以采取一些措施。</p>
<p>下图是原初访问**&#x2F;oauth&#x2F;token**获取token时，成功和失败（源码抛出异常时的响应示例）</p>
<p><img src="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316145452918.png" alt="image-20230316145452918"></p>
<p><img src="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316145519096.png" alt="image-20230316145519096"></p>
<h2 id="基于AOP的切点表示式"><a href="#基于AOP的切点表示式" class="headerlink" title="基于AOP的切点表示式"></a>基于AOP的切点表示式</h2><p>观察控制台日志：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">2023-03-16 14:55:08.940  WARN 25476 --- [io-63070-exec-5] o.s.s.o.p.e.TokenEndpoint                : Handling error: InvalidGrantException, 用户名或密码错误</span><br></pre></td></tr></table></figure>

<p>可以得到程序是在<strong>TokenEndpoint</strong>类中接受了处理，并返回了结果</p>
<p>阅读源码发现<img src="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316145920029.png" alt="image-20230316145920029"></p>
<p><strong>postAccessToken</strong>和<strong>handleException</strong>方法处理了信息的返回</p>
<p>那么思路很暴力很简单，切点表达式，直接对这两个方法做AOP处理</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Aspect</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AuthTokenAspect</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Around(&quot;execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Object <span class="title function_">handleControllerMethod</span><span class="params">(ProceedingJoinPoint pjp)</span> <span class="keyword">throws</span> Throwable &#123;</span><br><span class="line">        RestResponse&lt;Object&gt; response = <span class="keyword">new</span> <span class="title class_">RestResponse</span>&lt;&gt;();</span><br><span class="line">        <span class="type">Object</span> <span class="variable">proceed</span> <span class="operator">=</span> pjp.proceed();</span><br><span class="line">        <span class="keyword">if</span> (proceed != <span class="literal">null</span>) &#123;</span><br><span class="line">            ResponseEntity&lt;OAuth2AccessToken&gt; responseEntity = (ResponseEntity&lt;OAuth2AccessToken&gt;) proceed;</span><br><span class="line">            <span class="type">OAuth2AccessToken</span> <span class="variable">body</span> <span class="operator">=</span> responseEntity.getBody();</span><br><span class="line">            <span class="keyword">if</span> (responseEntity.getStatusCode().is2xxSuccessful()) &#123;</span><br><span class="line">                response.setCode(<span class="number">0</span>);</span><br><span class="line">                Map&lt;String, Object&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">                <span class="keyword">assert</span> body != <span class="literal">null</span>;</span><br><span class="line">                map.put(<span class="string">&quot;access_token&quot;</span>, body.getValue());</span><br><span class="line">                map.put(<span class="string">&quot;token_type&quot;</span>, body.getTokenType());</span><br><span class="line">                map.put(<span class="string">&quot;refresh_token&quot;</span>, body.getRefreshToken().getValue());</span><br><span class="line">                map.put(<span class="string">&quot;expires_in&quot;</span>, body.getExpiresIn());</span><br><span class="line">                map.put(<span class="string">&quot;scope&quot;</span>, body.getScope());</span><br><span class="line">                map.put(<span class="string">&quot;jti&quot;</span>, body.getAdditionalInformation().get(<span class="string">&quot;jti&quot;</span>));</span><br><span class="line">                response.setData(map);</span><br><span class="line">                response.setMsg(<span class="string">&quot;登录成功&quot;</span>);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                response.setCode(-<span class="number">1</span>);</span><br><span class="line">                response.setMsg(<span class="string">&quot;登录失败&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> ResponseEntity</span><br><span class="line">                .status(<span class="number">200</span>)</span><br><span class="line">                .body(response);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Around(&quot;execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.handleException(..))&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Object <span class="title function_">handleException</span><span class="params">(ProceedingJoinPoint pjp)</span> <span class="keyword">throws</span> Throwable &#123;</span><br><span class="line">        <span class="type">Object</span> <span class="variable">proceed</span> <span class="operator">=</span> pjp.proceed();</span><br><span class="line">        ResponseEntity&lt;OAuth2Exception&gt; response = (ResponseEntity&lt;OAuth2Exception&gt;) proceed;</span><br><span class="line">        <span class="keyword">return</span> ResponseEntity</span><br><span class="line">                .status(<span class="number">200</span>)</span><br><span class="line">                .body(RestResponse.validFail(Objects.requireNonNull(response.getBody()).getMessage()));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中，<code>RestResponse</code>是我自己封装的同意返回体</p>
<p>得到返回结果：</p>
<p><img src="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316150151554.png" alt="image-20230316150151554"></p>
<p><img src="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316150205344.png" alt="image-20230316150205344"></p>
<h2 id="基于全局MVC增强"><a href="#基于全局MVC增强" class="headerlink" title="基于全局MVC增强"></a>基于全局MVC增强</h2><p>本到这里就结束了，可笔者认为此方法不过完美，在网上得到了重写<code>/oauth/token</code>等MVC端点，再使用@ControllerAdvice增强来实现，十分优雅。故做此纪录：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;/oauth&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AuthorityController</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> TokenEndpoint tokenEndpoint;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Oauth2登录认证</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RequestMapping(value = &quot;/token&quot;, method = RequestMethod.POST)</span></span><br><span class="line">    <span class="keyword">public</span> RestResponse&lt;Oauth2TokenDto&gt; <span class="title function_">postAccessToken</span><span class="params">(Principal principal, <span class="meta">@RequestParam</span> Map&lt;String, String&gt; parameters)</span> <span class="keyword">throws</span> HttpRequestMethodNotSupportedException &#123;</span><br><span class="line">        <span class="type">OAuth2AccessToken</span> <span class="variable">oAuth2AccessToken</span> <span class="operator">=</span> tokenEndpoint.postAccessToken(principal, parameters).getBody();</span><br><span class="line">        <span class="type">Oauth2TokenDto</span> <span class="variable">oauth2TokenDto</span> <span class="operator">=</span> Oauth2TokenDto.builder()</span><br><span class="line">                .accessToken(oAuth2AccessToken.getValue())</span><br><span class="line">                .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())</span><br><span class="line">                .expiresIn(oAuth2AccessToken.getExpiresIn())</span><br><span class="line">                .tokenHead(<span class="string">&quot;Bearer &quot;</span>)</span><br><span class="line">                .scope(oAuth2AccessToken.getScope())</span><br><span class="line">                .jti(oAuth2AccessToken.getAdditionalInformation().get(<span class="string">&quot;jti&quot;</span>).toString()).build();</span><br><span class="line">        <span class="keyword">return</span> RestResponse.success(oauth2TokenDto);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里新建一个Controller类重写了postAccessToken的处理逻辑，并新建了OAuth2AccessToken类返回结果信息</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@Builder</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Oauth2TokenDto</span> &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 访问令牌</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String accessToken;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 刷新令牌</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String refreshToken;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 访问令牌头前缀</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String tokenHead;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 有效时间（秒）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> expiresIn;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 请求域</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> Set&lt;String&gt; scope;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * jti</span></span><br><span class="line"><span class="comment">     * JWT的唯一标识</span></span><br><span class="line"><span class="comment">     * 可避免重放攻击</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String jti;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对于异常信息，我直接定义一个全局异常来处理：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@ControllerAdvice</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">GlobalExceptionHandler</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ResponseBody</span><span class="comment">//将信息返回为 json格式</span></span><br><span class="line">    <span class="meta">@ExceptionHandler(Exception.class)</span><span class="comment">//此方法捕获Exception异常</span></span><br><span class="line">    <span class="meta">@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)</span><span class="comment">//状态码返回500</span></span><br><span class="line">    <span class="keyword">public</span> RestResponse&lt;String&gt; <span class="title function_">doException</span><span class="params">(Exception e)</span> &#123;</span><br><span class="line">        log.error(<span class="string">&quot;捕获异常：&#123;&#125;&quot;</span>, e.getMessage());</span><br><span class="line">        <span class="keyword">return</span> RestResponse.validFail(e.getMessage());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316154512487.png" alt="image-20230316154512487"></p>
<p><img src="https://0-bit.oss-cn-beijing.aliyuncs.com/image-20230316154522929.png" alt="image-20230316154522929"></p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>为了”统一规范“，这里造成了不少的牺牲，让代码侵入性变的很强，我认为不如和前端约定好，关于OAuth2的模块的返回结果进行针对性的处理。</p>

  </div>
</article>


    <div class="blog-post-comments">
        <div id="utterances_thread">
            <noscript>Please enable JavaScript to view the comments.</noscript>
        </div>
    </div>


        
          <div id="footer-post-container">
  <div id="footer-post">

    <div id="nav-footer" style="display: none">
      <ul>
         
          <li><a href="/">Home</a></li>
         
          <li><a href="/about/">About</a></li>
         
          <li><a href="/archives/">Articles</a></li>
         
          <li><a href="/categories/">Category</a></li>
         
          <li><a href="/search/">Search</a></li>
        
      </ul>
    </div>

    <div id="toc-footer" style="display: none">
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E4%BA%8EAOP%E7%9A%84%E5%88%87%E7%82%B9%E8%A1%A8%E7%A4%BA%E5%BC%8F"><span class="toc-number">2.</span> <span class="toc-text">基于AOP的切点表示式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E4%BA%8E%E5%85%A8%E5%B1%80MVC%E5%A2%9E%E5%BC%BA"><span class="toc-number">3.</span> <span class="toc-text">基于全局MVC增强</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">4.</span> <span class="toc-text">总结</span></a></li></ol>
    </div>

    <div id="share-footer" style="display: none">
      <ul>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.facebook.com/sharer.php?u=https://cheung0-bit.github.io/e4b16aee6d6d/"><i class="fab fa-facebook fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://twitter.com/share?url=https://cheung0-bit.github.io/e4b16aee6d6d/&text=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-twitter fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.linkedin.com/shareArticle?url=https://cheung0-bit.github.io/e4b16aee6d6d/&title=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-linkedin fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://pinterest.com/pin/create/bookmarklet/?url=https://cheung0-bit.github.io/e4b16aee6d6d/&is_video=false&description=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-pinterest fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=SpringSecurityOAuth2的自定义返回方案&body=Check out this article: https://cheung0-bit.github.io/e4b16aee6d6d/"><i class="fas fa-envelope fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://getpocket.com/save?url=https://cheung0-bit.github.io/e4b16aee6d6d/&title=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-get-pocket fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://reddit.com/submit?url=https://cheung0-bit.github.io/e4b16aee6d6d/&title=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-reddit fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.stumbleupon.com/submit?url=https://cheung0-bit.github.io/e4b16aee6d6d/&title=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-stumbleupon fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://digg.com/submit?url=https://cheung0-bit.github.io/e4b16aee6d6d/&title=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-digg fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.tumblr.com/share/link?url=https://cheung0-bit.github.io/e4b16aee6d6d/&name=SpringSecurityOAuth2的自定义返回方案&description="><i class="fab fa-tumblr fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://news.ycombinator.com/submitlink?u=https://cheung0-bit.github.io/e4b16aee6d6d/&t=SpringSecurityOAuth2的自定义返回方案"><i class="fab fa-hacker-news fa-lg" aria-hidden="true"></i></a></li>
</ul>

    </div>

    <div id="actions-footer">
        <a id="menu" class="icon" href="#" onclick="$('#nav-footer').toggle();return false;"><i class="fas fa-bars fa-lg" aria-hidden="true"></i> Menu</a>
        <a id="toc" class="icon" href="#" onclick="$('#toc-footer').toggle();return false;"><i class="fas fa-list fa-lg" aria-hidden="true"></i> TOC</a>
        <a id="share" class="icon" href="#" onclick="$('#share-footer').toggle();return false;"><i class="fas fa-share-alt fa-lg" aria-hidden="true"></i> Share</a>
        <a id="top" style="display:none" class="icon" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up fa-lg" aria-hidden="true"></i> Top</a>
    </div>

  </div>
</div>

        
        <footer id="footer">
  <div class="footer-left">
    Copyright &copy;
      
        
          2022-2024
            <a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/">
              苏ICP备2022044873号
            </a>
  </div>
  <div class="footer-right">
    <nav>
      <ul>
        
          <!--
       -->
          <li><a href="/">
              Home
            </a></li>
          <!--
     -->
          
          <!--
       -->
          <li><a href="/about/">
              About
            </a></li>
          <!--
     -->
          
          <!--
       -->
          <li><a href="/archives/">
              Articles
            </a></li>
          <!--
     -->
          
          <!--
       -->
          <li><a href="/categories/">
              Category
            </a></li>
          <!--
     -->
          
          <!--
       -->
          <li><a href="/search/">
              Search
            </a></li>
          <!--
     -->
          
      </ul>
    </nav>
  </div>
</footer>
    </div>
    <!-- styles -->


 
  <link
    rel="preload"
    href="/lib/font-awesome/css/all.min.css"
    as="style"
    onload="this.onload=null;this.rel='stylesheet'"
  />
  <noscript
    ><link
      rel="stylesheet"
      href="/lib/font-awesome/css/all.min.css"
  /></noscript>



    <!-- jquery -->
 
  
<script src="/lib/jquery/jquery.min.js"></script>





<!-- clipboard -->

   
    
<script src="/lib/clipboard/clipboard.min.js"></script>

  
  <script type="text/javascript">
  $(function() {
    // copy-btn HTML
    var btn = "<span class=\"btn-copy tooltipped tooltipped-sw\" aria-label=\"Copy to clipboard!\">";
    btn += '<i class="far fa-clone"></i>';
    btn += '</span>'; 
    // mount it!
    $(".highlight table").before(btn);
    var clip = new ClipboardJS('.btn-copy', {
      text: function(trigger) {
        return Array.from(trigger.nextElementSibling.querySelectorAll('.code')).reduce((str,it)=>str+it.innerText+'\n','')
      }
    });
    clip.on('success', function(e) {
      e.trigger.setAttribute('aria-label', "Copied!");
      e.clearSelection();
    })
  })
  </script>


<script src="/js/main.js"></script>

<!-- search -->

<!-- Google Analytics -->

<!-- Baidu Analytics -->

  <script type="text/javascript">
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?4484a4a33014b59670c470a6e15a66db";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
        </script>

<!-- Cloudflare Analytics -->

<!-- Umami Analytics -->

<!-- Disqus Comments -->

<!-- utterances Comments -->

    <script type="text/javascript">
      var utterances_repo = 'Cheung0-bit/blog-package';
      var utterances_issue_term = 'title';
      var utterances_label = 'Comment';
      var utterances_theme = 'github-dark';

      (function(){
          var script = document.createElement('script');

          script.src = 'https://utteranc.es/client.js';
          script.setAttribute('repo', utterances_repo);
          script.setAttribute('issue-term', 'pathname');
          script.setAttribute('label', utterances_label);
          script.setAttribute('theme', utterances_theme);
          script.setAttribute('crossorigin', 'anonymous');
          script.async = true;
          (document.getElementById('utterances_thread')).appendChild(script);
      }());
  </script>

</body>
</html>
